package com.wbtech.cobub;
import com.wbtech.cobub.model.Locations;
import com.wbtech.cobub.service.LocationService;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.telephony.gsm.GsmCellLocation;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class CellActivity extends Activity{

	private String MCC = "";
	private String MNC = "";
	private String LAC = "";
	private String CELLID = "";
	private String latitude = "";
	private String longitude = "";
	 @Override
	    public void onCreate(Bundle savedInstanceState) {
	        super.onCreate(savedInstanceState);
	        setContentView(R.layout.cell);
	        
	        try {
		        RefreshCellInfo();
			} catch (Exception e) {
				// TODO: handle exception
			}

	        TextView cellText = (TextView)findViewById(R.id.textCellInfo);
			cellText.setText("MNC:"+MNC + " MCC:"+MCC + "\nLAC:"+LAC + " CELLID:"+CELLID);
	        Button btnSearch = (Button)findViewById(R.id.btnSearch);
	        btnSearch.setOnClickListener(new OnClickListener() {

				public void onClick(View v) {
					if(MNC.equals(""))
		    		{
		    			Toast.makeText(getApplicationContext(), "基站信息不能为空", Toast.LENGTH_SHORT).show();
		    			return;
		    		}
					
					WSAsyncTask task = new WSAsyncTask();
		    		task.execute();				
				}
			});
	        
	        Button btnMap = (Button)findViewById(R.id.btnViewMap);
		      btnMap.setOnClickListener(new OnClickListener() {					
					public void onClick(View v) {
						if(latitude.equals("")||longitude.equals(""))
						{
							Toast.makeText(getApplicationContext(), "当前无GPS数据", Toast.LENGTH_SHORT).show();
							return;
						}
						Intent mapIntent = new Intent(CellActivity.this,MapsActivity.class);
						mapIntent.putExtra("latitude", latitude);
						mapIntent.putExtra("longitude", longitude);
						startActivity(mapIntent);
					}
				});
	    }


	private void RefreshCellInfo() {
		try {
			TelephonyManager tm = (TelephonyManager)
			this.getSystemService(Context.TELEPHONY_SERVICE);//
			
			GsmCellLocation location = (GsmCellLocation)tm.getCellLocation();
			LAC = String.valueOf(location.getLac());
			CELLID = String.valueOf(location.getCid());
			
			String MCCMNC = tm.getNetworkOperator();
			
			MNC = MCCMNC.substring(0,3);
			MCC = Integer.valueOf(MCCMNC.substring(3)).toString();
			
			
		} catch (Exception e) {
			// TODO: handle exception
		}
		
	}
	 
	 
	
	 class WSAsyncTask extends AsyncTask
	    {
	    	ProgressDialog dialog = null;

	    	protected Object doInBackground(Object... params)
	    	{
	    		RefreshCellInfo();
				Locations loation = LocationService.GetAddressByCellID(MNC, MCC, LAC, CELLID, "zh-CN");
				return loation;
	    	}

	    	@Override
			protected void onPreExecute() {
				super.onPreExecute();
				dialog = new ProgressDialog(CellActivity.this);
				dialog.setCancelable(false);
				dialog.setTitle("地址查询...");
				dialog.setMessage("查询中,请稍候...");
				dialog.show();
			}

			@Override
			protected void onPostExecute(Object result) {
				super.onPostExecute(result);
		        setProgressBarIndeterminateVisibility(false);
				dialog.dismiss();
				TextView cellText = (TextView)findViewById(R.id.textCellInfo);
				cellText.setText("MNC:"+MNC + " MCC:"+MCC + "\nLAC:"+LAC + " CELLID:"+CELLID);
				Locations ret = (Locations)result;
				if(ret.getFlag() == null || ret.getMsg() == null)
				{
					Dialog messageDialog = buildMessageDialog(CellActivity.this,"查询失败,当前网络较慢或无连接，请稍后重试....");
					messageDialog.show();
				}
				else if(ret.getFlag())
				{
					   ((TextView)findViewById(R.id.textLatitudeValue)).setText(ret.getLatitude());
					   ((TextView)findViewById(R.id.textLongitudeValue)).setText(ret.getLongitude());
					   latitude = ret.getLatitude();
					   longitude = ret.getLongitude();
					        
				       ((TextView)findViewById(R.id.textCountryValue)).setText(ret.getCountry());
				       ((TextView)findViewById(R.id.textRegionValue)).setText(ret.getRegion());
				       ((TextView)findViewById(R.id.textCountryValue)).setText(ret.getCounty());
				       ((TextView)findViewById(R.id.textCitryValue)).setText(ret.getCity());
				       ((TextView)findViewById(R.id.textStreetValue)).setText(ret.getStreet());
				       ((TextView)findViewById(R.id.textStreetNumberValue)).setText(ret.getStreetNumber());
				       ((TextView)findViewById(R.id.textPostalCodeValue)).setText(ret.getPostalcode());
				       ((TextView)findViewById(R.id.textCountryValue)).setText(ret.getCountry());
				}
				else
				{
					Dialog messageDialog = buildMessageDialog(CellActivity.this,ret.getMsg());
					messageDialog.show();
				}
			}
	    }
	  
	  
	 private Dialog buildMessageDialog(Context context,String message) {
			AlertDialog.Builder builder = new AlertDialog.Builder(context);
			builder.setIcon(R.drawable.icon);
			builder.setTitle("Cobub提示");
			builder.setMessage(message);
			builder.setPositiveButton("确定",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int whichButton) {
							setTitle("Cobub提示");
						}
					});
			return builder.create();

		}
	  
	  private Dialog ExitDialog(Context context) {
			AlertDialog.Builder builder = new AlertDialog.Builder(context);
			builder.setIcon(R.drawable.icon);
			builder.setTitle("Cobub提示");
			builder.setMessage("确定退出么?");
			builder.setPositiveButton("确定",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int whichButton) {
							finish();
						}
					});
			builder.setNegativeButton("取消",
					new DialogInterface.OnClickListener() {
						public void onClick(DialogInterface dialog, int whichButton) {

						}
					});
			return builder.create();
		}

	    @Override
		public boolean onKeyDown(int keyCode, KeyEvent event) {
			if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
				ExitDialog(CellActivity.this).show();
				return true;
			}
			return super.onKeyDown(keyCode, event);
		}
	  
}
